package com.henry.magicsquare;

import java.io.*;
import java.util.Arrays;

public class MagicSquareTest {

    public static boolean testMagicSquare(Square square) {
        int constantValue = square.rowSum(0);
        for (int i = 1; i < square.getRows(); i++) if (square.rowSum(i) != constantValue) return false;
        for (int i = 0; i < square.getCols(); i++) if (square.colSum(i) != constantValue) return false;
        return square.diagonalSum() == constantValue && square.backDiagonalSum() == constantValue;
    }

    public static Square loadSquareFromFile(String filePath) throws FileNotFoundException {
        File file = new File(filePath);
        BufferedReader reader = new BufferedReader(new FileReader(file));

        StringBuilder fileContents = new StringBuilder();

        String line;
        try {
            while ((line = reader.readLine()) != null) {
                fileContents.append(line.trim());
                fileContents.append("\t");
            }
        } catch (IOException e) {
            System.out.println(e.toString());
        }

        String[] integersAsStrings = fileContents.toString().split("\\t+");

        int[] data = Arrays.stream(integersAsStrings).mapToInt(Integer::parseInt).toArray();

        return new Square((int)(Math.sqrt(data.length)), data);
    }

    public static void main(String[] args) {
        String pathPrefix = "src/main/resources/MagicSquares/";
        String[] filesNames = {"Luna.txt", "Mercury.txt"};
        for (String filename : filesNames) {
            String filePath = pathPrefix + filename;
            try {
                Square mat = loadSquareFromFile(filePath);
                System.out.println(testMagicSquare(mat));
            } catch (FileNotFoundException e) {
                System.out.println(e.toString());
            }
        }
    }
}
